package com.symaster.common.swing.element.text.area;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;

/**
 * @author yinmiao
 * @date 2021-07-29 16:24
 */
public class LimitativeDocument extends PlainDocument {

    private final JTextComponent textComponent;
    private int lineMax = 100;

    public LimitativeDocument(JTextComponent tc, int lineMax) {
        this.textComponent = tc;
        this.lineMax = lineMax;
    }

    public LimitativeDocument(JTextComponent tc) {
        this.textComponent = tc;
    }

    public void insertString(int offset, String s, AttributeSet attributeSet) throws BadLocationException {
        String value = this.textComponent.getText();
        int overrun = 0;
        if (value != null && value.indexOf(10) >= 0 && value.split("\n").length >= this.lineMax) {
            overrun = value.indexOf(10) + 1;
            super.remove(0, overrun);
        }

        super.insertString(offset - overrun, s, attributeSet);
    }
}
